package com.ruicar.afs.cloud.channel.register.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.channel.affiliation.service.ChannelBaseInfoTempService;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskAssign;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskCreated;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskAssignService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskCreatedService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.common.condition.BaseInfoTypeDTO;
import com.ruicar.afs.cloud.channel.common.dto.CarAllListDTO;
import com.ruicar.afs.cloud.channel.common.dto.CarInfoListDTO;
import com.ruicar.afs.cloud.channel.common.dto.CarToListDTO;
import com.ruicar.afs.cloud.channel.common.entity.CarToList;
import com.ruicar.afs.cloud.channel.common.entity.FileList;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.feign.ListBaseFeign;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToApply;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToApplyImpl;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.common.until.ChannelRoleEnum;
import com.ruicar.afs.cloud.channel.common.until.RoleTypeDic;
import com.ruicar.afs.cloud.channel.filetemp.entity.ComAttachementFileTemp;
import com.ruicar.afs.cloud.channel.filetemp.service.ComAttachementFileTempService;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.register.condition.ChannelListingCarRelTempCondition;
import com.ruicar.afs.cloud.channel.register.condition.ChannelListingCarTempCondition;
import com.ruicar.afs.cloud.channel.register.condition.SubmitDTO;
import com.ruicar.afs.cloud.channel.register.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.channel.register.entity.ChannelListingCar;
import com.ruicar.afs.cloud.channel.register.entity.ChannelListingCarTemp;
import com.ruicar.afs.cloud.channel.register.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.channel.register.service.ChannelListingCarService;
import com.ruicar.afs.cloud.channel.register.service.ChannelListingCarTempService;
import com.ruicar.afs.cloud.channel.register.utils.RegisterDic;
import com.ruicar.afs.cloud.channel.register.vo.CarRule;
import com.ruicar.afs.cloud.channel.register.vo.ChannelListingCarTempVo;
import com.ruicar.afs.cloud.channel.register.vo.PrintCar;
import com.ruicar.afs.cloud.channel.witness.entity.ChannelWitnessInfoTemp;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.enums.ChannelNode;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.config.FileProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.vo.ComAttachmentFileDataVo;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.QueryFLowCmdRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.TaskSubmitRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowCmdBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/carRel")
@Api(value = "carRel", description = "挂靠车备案管理模块")
public class ChannelListingCarTempController {
    private static final Logger logger = LoggerFactory.getLogger(ChannelListingCarTempController.class);

    private ChannelListingCarTempService channelListingCarTempService;

    private final TsysAddressParamService service;

    private ChannelBaseInfoTempService channelBaseInfoTempService;

    private ListBaseFeign listBaseFeign;

    private final WorkTaskDetailService workTaskDetailService;

    private final UidGenerator uidGenerator;
    private final WorkflowService workflowService;
    private final WorkTaskAssignService workTaskAssignService;
    private final WorkTaskCreatedService workTaskCreatedService;
    private ChannelUseCaseService channelUseCaseService;
    private ChannelConfig channelConfig;

    private final ComPrintFormManageService comPrintFormManageService;
    private final ComAttachmentFileService comAttachmentFileService;
    private FileProperties fileProperties;
    private final TsysAddressParamService tsysAddressParamService;

    private final ComAttachementFileTempService comAttachementFileTempService;
    private final SenderChannelToApplyImpl senderChannelToApplyImpl;
    private final SenderChannelToApply senderChannelToApply;

    private final ChannelListingCarService channelListingCarService;

    @PostMapping("/getChannelListingCarTemp")
    @ApiOperation(value = "分页获取挂靠车数据")
    public IResponse<IPage<ChannelListingCarTempVo>> getChannelListingCarTemp(@RequestBody ChannelListingCarRelTempCondition channel) {
        //  businessType：01是新车  02 二手车  03是非直营新车二手车都有
        // ownBusinessType ：01是新车  02 二手车  03  是直营新车二手车都有

        // 第一步我要知道登录者的角色属性  是属于直营还是非直营
        List<String> role =SecurityUtils.getRoles();
        BaseInfoTypeDTO dto =new BaseInfoTypeDTO();
        if(role.contains(ChannelRoleEnum.ROLE_ADMIN.name())){
            // 说明进来的是管理员
            dto.setBusinessType(RoleTypeDic.NEW_CAR);
            dto.setOwnBusinessType(RoleTypeDic.NEW_CAR);
        }else {
            if(role.contains(ChannelRoleEnum.ROLE_OTHER_MANAGE_LISTING.name())||role.contains(ChannelRoleEnum.ROLE_OTHER_SEE_LISTING.name())){
                // 说明我有非直营权限
                dto.setBusinessType(RoleTypeDic.NEW_CAR);
            }
            if(role.contains(ChannelRoleEnum.ROLE_OWN_MANAGE_LISTING.name())||role.contains(ChannelRoleEnum.ROLE_OWN_SEE_LISTING.name())){
                // 说明我有直营权限
                dto.setOwnBusinessType(RoleTypeDic.NEW_CAR);
            }
        }
        if((dto.getBusinessType()==null||dto.getBusinessType()=="")&&(dto.getOwnBusinessType()==null||dto.getOwnBusinessType()=="")){
            return IResponse.fail("暂无权限查询！");
        }
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("clientId",channelConfig.getCaseClientId());
        headers.put("clientSecret",channelConfig.getCaseClientSecret());
        IResponse result=channelUseCaseService.getBaseInfoByRole(dto,headers);

        IPage<List<ChannelListingCarTempVo>> list=null;
        Page page = new Page(channel.getPageNumber(), channel.getPageSize());
        // 声明一个 合作商id 集合
        List<Long> ids =new ArrayList<>();
        if("0000".equals(result.getCode())){
            List<ChannelBaseInfoTemp> base= JSON.parseArray(JSON.toJSONString(result.getData()), ChannelBaseInfoTemp.class);
            if(base.size()>0){
                for (int i=0;i<base.size();i++){
                    ids.add(base.get(i).getId());
                }
                list=channelListingCarTempService.getNewChannelListingCarTemp(page,channel,ids);
            }
        }else {
            throw new AfsBaseException("查询合作商失败！");
        }

        return IResponse.success(list);

    }

    @PostMapping("/getApplyListingCarTemp")
    @ApiOperation(value = "进件分页获取挂靠车数据")
    public IResponse<IPage<ChannelListingCarTempVo>> getApplyListingCarTemp(@RequestBody ChannelListingCarRelTempCondition channel) {

        Page page = new Page(channel.getPageNumber(), channel.getPageSize());
        IPage<List<ChannelListingCarTempVo>> list=channelListingCarTempService.getApplyListingCarTemp(page,channel);
        return IResponse.success(list);

    }

    @PostMapping("/getRegister")
    @ApiOperation(value = "分页获取挂靠车审核列表")
    public IResponse<IPage<ChannelListingCarTempVo>> getRegister(@RequestBody ChannelListingCarRelTempCondition channel) {
        // 先获取登陆人的角色
        List<String> roles =SecurityUtils.getRoles();
        if(roles.size()<=0){
            throw new AfsBaseException("此用户暂无权限查询！");
        }
        // 先去查询 待审批的数据信息
        Page page = new Page(channel.getPageNumber(), channel.getPageSize());
        IPage<List<ChannelListingCarTempVo>>  list =channelListingCarTempService.getRegister(page, channel,roles, AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_REGISTER));
        return IResponse.success(list);

    }

    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对应的数据")
    public IResponse<ChannelListingCarTempVo> getById(@RequestBody ChannelListingCarTempVo channel) {

        if (channel.getId() == null) {
            return IResponse.fail("查询失败，请联系管理员！");
        }
        List<ChannelListingCarTempVo> list = channelListingCarTempService.getCarById(channel.getId());

        if (list.size() == 1) {
            ChannelListingCar listingCar =channelListingCarService.getById(list.get(0).getId());
            if(listingCar!=null){
                list.get(0).setFirstReturn("0");
            }
            return IResponse.success("查询成功").setData(list.get(0));
        } else {
            return IResponse.fail("查询失败，请联系管理员！");
        }

    }

    @Transactional
    @PostMapping("/toExamine")
    @ApiOperation(value = "挂牌车审核")
    public IResponse toExamine(@RequestBody ChannelListingCarTemp carRelTemp) throws JsonProcessingException {
        ChannelListingCarTemp aa = channelListingCarTempService.getById(carRelTemp.getId());

        WorkTaskDetail work =workTaskDetailService.list(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBusinessKey, carRelTemp.getId()).eq(WorkTaskDetail::getBizDataId,aa.getDataId().toString())).get(0);
        if (RegisterDic.STATUS_PASS.equals(carRelTemp.getStatus())) {
            channelListingCarTempService.update(Wrappers.<ChannelListingCarTemp>lambdaUpdate().set(ChannelListingCarTemp::getStartStopReason,null).eq(ChannelListingCarTemp::getId, carRelTemp.getId()));

            // 去更新影像件信息===========
            comAttachementFileTempService.remove(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachementFileTemp::getBelongNo, ChannelNode.carRecordApply.toString()));
            //把影像资料存储
            List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.carRecordApply.toString()));
            if(fileList.size()>0){
                for(ComAttachmentFile file:fileList){
                    ComAttachementFileTemp fileTemp=new ComAttachementFileTemp();
                    BeanUtils.copyProperties(file, fileTemp);
                    fileTemp.setId(null);
                    comAttachementFileTempService.save(fileTemp);
                }
            }

            // 如果是通过
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(carRelTemp.getId());
            dto.setApprove("1");
            dto.setBizDataId(work.getBizDataId());
            submit(dto);

        }else if(RegisterDic.STATUS_RETURN.equals(carRelTemp.getStatus())){
            // 这边进来是退回
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(carRelTemp.getId());
            dto.setApprove("2");
            dto.setBizDataId(work.getBizDataId());

            submit(dto);


        }else if(RegisterDic.STATUS_REFUSE.equals(carRelTemp.getStatus())){
            // 先删除自己的数据
            comAttachmentFileService.remove(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.carRecordApply.toString()));
            // 去修改进件的影像资料
            List<ComAttachementFileTemp> list=comAttachementFileTempService.list(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.carRecordApply.toString()));
            for(ComAttachementFileTemp fileTemp:list){
                ComAttachmentFile file=new ComAttachmentFile();
                BeanUtils.copyProperties(fileTemp, file);
                file.setId(null);
                comAttachmentFileService.save(file);
            }
            if(list.size()>0){
                List<ComAttachmentFile> list2 = JSONUtil.parseArray(list).toList(ComAttachmentFile.class);
                ComAttachmentFileDataVo dataVo=new ComAttachmentFileDataVo();
                dataVo.setComAttachmentFileList(list2);
                AfsTransEntity<ComAttachmentFileDataVo> transEntity = new AfsTransEntity<>();
                transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_CHANNEL_FILE_APPLY);
                transEntity.setData(dataVo);
                senderChannelToApply.sendWitnessFile(transEntity);
            }



            // 这边进来是拒绝
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(carRelTemp.getId());
            dto.setApprove("3");
            dto.setBizDataId(work.getBizDataId());

            submit(dto);
        }

        aa.setStatus(carRelTemp.getStatus());
        aa.setUpdateBy(SecurityUtils.getUsername());
        aa.setUpdateTime(new Date(System.currentTimeMillis()));
        aa.setApprovalTime(new Date(System.currentTimeMillis()));
        if(RegisterDic.STATUS_PASS.equals(carRelTemp.getStatus())){
            aa.setEvaluationPrice(carRelTemp.getEvaluationPrice());
            aa.setValidityDays(carRelTemp.getValidityDays());
        }
        Boolean result=channelListingCarTempService.updateById(aa);
        ChannelListingCarTemp temp=channelListingCarTempService.getById(aa.getId());
        if(RegisterDic.STATUS_PASS.equals(temp.getStatus())){
            // 去名单库更新数据
            this.sendStorehouse(temp);
        }
        if(RegisterDic.STATUS_REFUSE.equals(carRelTemp.getStatus())){
            // 先去判断下这个挂牌车之前的数据
            // 第一步先通过VIN 和渠道id 查找唯一数据
//            CarInfoListDTO condition = new CarInfoListDTO();
//            condition.setPageNum(1);
//            condition.setPageSize(10);
//            condition.setVinNumber(aa.getVin());
//            condition.setPartnerId(aa.getChannelId().toString());
//            CarAllListDTO carVo = new CarAllListDTO();
//            carVo.setType("tb_car_info");
//            carVo.setData(condition);
//            JSONObject code = listBaseFeign.carListingSelecte(carVo);
//            // 看一看有没有数据
//            if ("200".equals(code.get("code").toString())) {
//                JSONObject data = code.getJSONObject("data");
//                Integer total = data.getInteger("total");
//                // 判断有没有  0  就添加
//                 if (total == 1) {
//                    // 声明一个参数封装类
//                    List<CarToList> carList = data.getJSONArray("rows").toJavaList(CarToList.class);
//                    aa.setBrand(carList.get(0).getBrand());
//                    aa.setCarType(carList.get(0).getVehicleType());
//                    aa.setModel(carList.get(0).getModel());
//                    aa.setStyle(carList.get(0).getStyle());
//                    aa.setFuelType(carList.get(0).getFuelType());
//                    aa.setCardCity(carList.get(0).getCardCity());
//                    aa.setCardProvince(carList.get(0).getCardProvince());
//                    aa.setApparentMileage(carList.get(0).getApparentMileage());
//                    aa.setFirstLicensePlateDate(carList.get(0).getFirstRegistrationDate());
//                    aa.setManufactureDate(carList.get(0).getVehicleDeliveryDate());
//                    aa.setOwnerName(carList.get(0).getOwner());
//                    aa.setOwnerCardId(carList.get(0).getIdNo());
//                    aa.setUseCharacter(carList.get(0).getOriginalUseNature());
//                    aa.setGuidancePrice(carList.get(0).getGuidancePrice());
//                    aa.setOutputVolume(carList.get(0).getDisplacement());
//                    aa.setEngineNumber(carList.get(0).getEngineNumber());
//                    aa.setBodyColor(carList.get(0).getCarColor());
//                    aa.setTransferNumber(carList.get(0).getTotalTransferTimes());
//                    aa.setCarNumber(carList.get(0).getLicensePlateNumber());
//                    if("1".equals(carList.get(0).getStatus())){
//                    aa.setStatus(RegisterDic.STATUS_PASS);
//                    }else {
//                        aa.setStatus(RegisterDic.STATUS_STOP);
//                    }
//                    aa.setApprovalTime(carList.get(0).getApplicationTime());
//                    aa.setUseCarNumber(carList.get(0).getUseCarNumber());
//                    aa.setBrandId(carList.get(0).getBrandId());
//                    aa.setModelId(carList.get(0).getModelId());
//                    aa.setStyleId(carList.get(0).getStyleId());
//                    aa.setInvoiceTime(carList.get(0).getInvoiceTime());
//
//
//                }
//            }else {
//
//            }

            // 这边去看正式表有没有数据，如果有就数据回滚
            ChannelListingCar listingCar=channelListingCarService.getById(temp.getId());
            if(listingCar!=null){
                BeanUtils.copyProperties(listingCar, temp);
                channelListingCarTempService.updateById(temp);
            }
        }
        return result ? IResponse.success("成功") : IResponse.fail("失败");
    }

    public void submit(SubmitDTO dto) throws JsonProcessingException {
        log.info("参数;"+dto.getBizDataId());
        WorkTaskAssign assgin = workTaskAssignService.getOne(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, dto.getBizDataId()));
        WorkTaskCreated created = workTaskCreatedService.getOne(Wrappers.<WorkTaskCreated>query().lambda().eq(WorkTaskCreated::getBizDataId, dto.getBizDataId()));
        WorkTaskDetail detail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBizDataId, dto.getBizDataId()));
        //提交完成之后删除其他人员代办
        List<WorkTaskAssign> assignList = workTaskAssignService.list(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, dto.getBizDataId()));
        //删除剩余节点数据信息
            for(int i=0;i<assignList.size();i++){
                workTaskAssignService.removeById(assignList.get(i).getId().toString());
            }
        logger.info("流程id"+dto.getBizDataId());
        logger.info("数据id"+dto.getRegisterId());
        logger.info("处理人"+SecurityUtils.getUsername());
        TaskSubmitRequest taskSubmitRequest = new TaskSubmitRequest();
        taskSubmitRequest.setGwtUserId(assgin.getAssignId());
        taskSubmitRequest.setAfsFlowKey(created.getAfsFlowKey());
        taskSubmitRequest.setBizDataId(created.getBizDataId());
        QueryFLowCmdRequest request = new QueryFLowCmdRequest();
        request.setFlowInstanceId(created.getFlowInstanceId());
        WorkFlowResponse<List<FlowCmdBean>> cmdResponse = workflowService.queryFlowCmd(request);
        List<FlowCmdBean> cmdList = cmdResponse.getAfsData();
        FlowCmdBean cmd = workTaskCreatedService.channelApprove(dto.getApprove(),cmdList);

        ChannelListingCarTemp temp =channelListingCarTempService.getById(dto.getRegisterId());
        if(cmd!=null){
            log.info("==================================提交工作流开始==================================》");
            taskSubmitRequest.setCmdId(cmd.getId());
            ObjectMapper mapper = new ObjectMapper();
            //获取配置节点信息
            String json = mapper.writeValueAsString(temp);
            JSONObject cancelJson = JSONObject.parseObject(json);
            workflowService.taskSubmit(taskSubmitRequest,cancelJson);


        }else {
            throw new AfsBaseException("提交工作流失败！");
        }
    }

    // 单独写法方法用于推名单库
    public void sendStorehouse(ChannelListingCarTemp channel){
        // 推名单库之前把数据存正式表
        ChannelListingCar listingCar=channelListingCarService.getById(channel.getId());
        if(listingCar==null){
            // 没有去保存
            listingCar=new ChannelListingCar();
            BeanUtils.copyProperties(channel, listingCar);
            channelListingCarService.save(listingCar);
        }else {
            BeanUtils.copyProperties(channel, listingCar);
            channelListingCarService.updateById(listingCar);
        }


        // 第一步先通过VIN 和渠道id 查找唯一数据
        CarInfoListDTO condition = new CarInfoListDTO();
        condition.setPageNum(1);
        condition.setPageSize(10);
        condition.setVinNumber(channel.getVin());
        condition.setPartnerId(channel.getChannelId().toString());
        CarAllListDTO carVo = new CarAllListDTO();
        carVo.setType("tb_car_info");
        carVo.setData(condition);
        JSONObject code = listBaseFeign.carListingSelecte(carVo);



        // 如果是通过 请更新挂牌车名单库
        CarToList car = new CarToList();
        car.setApiUser("apiUser");
        car.setApparentMileage(channel.getApparentMileage());
        car.setApplicationTime(channel.getCreateTime());
        car.setBrand(channel.getBrand());
        car.setCarColor(channel.getBodyColor());
        car.setCreateBy(channel.getCreateBy());
        car.setCreateTime(channel.getCreateTime());
        car.setDisplacement(channel.getOutputVolume());
        car.setEngineNumber(channel.getEngineNumber());
        car.setFirstRegistrationDate(channel.getFirstLicensePlateDate());
        car.setFuelType(channel.getFuelType());
        car.setGuidancePrice(channel.getGuidancePrice());
        car.setIdNo(channel.getOwnerCardId());
        car.setLicensePlateNumber(channel.getCarNumber());
        car.setUseCarNumber(channel.getUseCarNumber());
        car.setBrandId(channel.getBrandId());
        car.setModelId(channel.getModelId());
        car.setStyleId(channel.getStyleId());
        car.setInvoiceTime(channel.getInvoiceTime());
        // 上牌省市
        car.setCardProvince(channel.getCardProvince());
        car.setCardCity(channel.getCardCity());
        car.setListedProvincesCities(channel.getCardCity());
        car.setModel(channel.getModel());
        car.setOriginalUseNature(channel.getUseCharacter());
        car.setOwner(channel.getOwnerName());
        car.setEvaluationPrice(channel.getEvaluationPrice());
        // 根据合作商id 查询合作商名称
        ChannelBaseInfoTemp temp2 = channelBaseInfoTempService.getById(channel.getChannelId());
        if(temp2==null){
            throw new AfsBaseException("合作商信息异常!请更换！");
        }
        car.setPartnerId(channel.getChannelId().toString());
        car.setPartnerName(temp2.getChannelFullName());
        if(RegisterDic.STATUS_PASS.equals(channel.getStatus())){
            car.setStatus("1");
        }else if(RegisterDic.STATUS_STOP.equals(channel.getStatus())){
            car.setStatus("0");
        }
        car.setTotalTransferTimes(channel.getTransferNumber());
        car.setStyle(channel.getStyle());
        car.setUpdateBy(SecurityUtils.getUsername());
        car.setUpdateTime(new Date(System.currentTimeMillis()));
        car.setVehicleType(channel.getCarType());
        car.setVehicleDeliveryDate(channel.getManufactureDate());
        car.setVehicleTypeId(null);
        car.setVinNumber(channel.getVin());
        // 声明一个附件
        List<FileList> fList = new ArrayList<>();
        FileList fileList = new FileList();
        fileList.setName("");
        fileList.setPath("");
        fList.add(fileList);

        // 看一看有没有数据
        if ("200".equals(code.get("code").toString())) {
            JSONObject data = code.getJSONObject("data");
            Integer total = data.getInteger("total");
            // 判断有没有  0  就添加
            if (total == 0) {
                // 声明一个参数封装类
                CarToListDTO vo = new CarToListDTO();
                vo.setType("tb_car_info");
                vo.setData(car);
                vo.setFileList(fList);
                // 这边是没有 要进行添加
                JSONObject json = listBaseFeign.carListingSave(vo);
                if (!"200".equals(json.get("code").toString())) {
                    throw new AfsBaseException("更新名单库失败！");
                }
            } else if (total == 1) {
                // 声明一个参数封装类
                List<CarToList> ids = data.getJSONArray("rows").toJavaList(CarToList.class);
                car.setId(ids.get(0).getId());
                CarToListDTO vo = new CarToListDTO();
                vo.setType("tb_car_info");
                vo.setData(car);
                vo.setFileList(fList);
                // 这边是有需要修改
                JSONObject json = listBaseFeign.carListingUpdate(vo);
                if (!"200".equals(json.get("code").toString())) {
                    throw new AfsBaseException("更新名单库失败！");
                }
            }
        }
    }


    @Transactional
    @PostMapping("/save")
    @ApiOperation(value = "保存数据")
    public IResponse<ChannelListingCarTemp> save(@RequestBody ChannelListingCarTempCondition channel) throws ParseException {
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());

            if (channel.getChannelId() == null) {
                return IResponse.fail("请选择合作商！");
            }
        List<String> statusList =new ArrayList<>();
        statusList.add(RegisterDic.STATUS_STOP);
        statusList.add(RegisterDic.STATUS_REFUSE);
        statusList.add(RegisterDic.STATUS_ZORO_DRAFT);
        // 先查看这个VIN在其他挂靠单位有没有未失效的备案信息
        if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getChannelId, channel.getChannelId()).notIn(ChannelListingCarTemp::getStatus, statusList)).size() > 0) {
                return IResponse.fail("该挂牌车在其他合作商存在未失效的备案信息！");
            }
            // 查询自己有没有未失效的备案信息
            List<ChannelListingCarTemp> list = channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getStatus, statusList));
            if (list.size() > 0) {
                return IResponse.fail("该挂牌车已存在未失效的备案信息！");
            } else {
                // 再去看看这个公司有没有失效的这辆车挂牌信息
                if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).eq(ChannelListingCarTemp::getChannelId, channel.getChannelId()).eq(ChannelListingCarTemp::getStatus, RegisterDic.STATUS_STOP)).size() > 0) {
                    return IResponse.fail("曾经备案过该车，并且已经停用，请从新修改车辆状态！");
                } else {
                    // 如果没有那么就加入挂牌车表和挂牌车关联表
                    channel.setCreateTime(new Date(System.currentTimeMillis()));
                    channel.setDelFlag(RegisterDic.DEL_FLAG_USABLE);
                    channel.setCreateBy(SecurityUtils.getUsername());
                    channel.setMsgSource(RegisterDic.sourceChannel);
                    channel.setChannelBelong(baseInfoTemp.getChannelBelong());
                    if(RegisterDic.STATUS_PASS.equals(channel.getStatus())){
                        channel.setApprovalTime(new Date(System.currentTimeMillis()));
                    }
                    channelListingCarTempService.save(channel);

                    // 如果是通过那么就同步到名单库
                    ChannelListingCarTemp temp=channelListingCarTempService.getById(channel.getId());
                    if(RegisterDic.STATUS_PASS.equals(temp.getStatus())){

                        comAttachementFileTempService.remove(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,channel.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.carRecordApply.toString()));
                        //把影像资料存储
                        List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,channel.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.carRecordApply.toString()));
                        if(fileList.size()>0){
                            for(ComAttachmentFile file:fileList){
                                ComAttachementFileTemp fileTemp=new ComAttachementFileTemp();
                                BeanUtils.copyProperties(file, fileTemp);
                                fileTemp.setId(null);
                                comAttachementFileTempService.save(fileTemp);
                            }
                        }
                        this.sendStorehouse(channel);
                    }
                    return IResponse.success(Boolean.TRUE).setMsg("录入成功").setData(channel);
                }
            }

    }

    @Transactional
    @PostMapping("/applySave")
    @ApiOperation(value = "进件保存数据")
    public IResponse<ChannelListingCarTemp> applySave(@RequestBody ChannelListingCarTemp channel) throws ParseException, JsonProcessingException {
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());
            if (channel.getChannelId() == null) {
                return IResponse.fail("请选择合作商！");
            }
        List<String> statusList =new ArrayList<>();
        statusList.add(RegisterDic.STATUS_STOP);
        statusList.add(RegisterDic.STATUS_REFUSE);
        statusList.add(RegisterDic.STATUS_ZORO_DRAFT);
        // 先查看这个VIN在其他挂靠单位有没有未失效的备案信息
        if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getChannelId, channel.getChannelId()).notIn(ChannelListingCarTemp::getStatus, statusList)).size() > 0) {
                return IResponse.fail("该挂牌车在其他合作商存在未失效的备案信息！");
            }
            // 查询自己有没有未失效的备案信息
            List<ChannelListingCarTemp> list = channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getStatus, statusList));
            if (list.size() > 0) {
                return IResponse.fail("该挂牌车已存在未失效的备案信息！");
            } else {
                // 再去看看这个公司有没有失效的这辆车挂牌信息
                if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).eq(ChannelListingCarTemp::getChannelId, channel.getChannelId()).eq(ChannelListingCarTemp::getStatus, RegisterDic.STATUS_STOP)).size() > 0) {
                    return IResponse.fail("曾经备案过该车，并且已经停用，请从新修改车辆状态！");
                } else {
                    // 如果没有那么就加入挂牌车表和挂牌车关联表
                    channel.setCreateTime(new Date(System.currentTimeMillis()));
                    channel.setDelFlag(RegisterDic.DEL_FLAG_USABLE);
                    channel.setCreateBy(SecurityUtils.getUsername());
                    channel.setMsgSource(RegisterDic.sourceApply);
                    channel.setChannelBelong(baseInfoTemp.getChannelBelong());
                    channelListingCarTempService.save(channel);
                    // 如果是审核中 那么就进入工作流
                    if(RegisterDic.STATUS_APPROVE.equals(channel.getStatus())){
                        this.foundWorkFlow(channel);
                    }

                    return IResponse.success(Boolean.TRUE).setMsg("录入成功").setData(channel);
                }

            }

    }


    @Transactional
    @PostMapping("/edit")
    @ApiOperation(value = "修改数据")
    public IResponse<ChannelListingCarTemp> edit(@RequestBody ChannelListingCarTemp channel) throws ParseException, JsonProcessingException {
        if (channel.getChannelId() == null) {
            return IResponse.fail("请选择合作商！");
        }
        // 获取关联表id
        if (channel.getId() == null) {
            return IResponse.fail("请正确信息后修改！");
        }
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());
        ChannelListingCarTemp temp = channelListingCarTempService.getById(channel.getId());

        //修改前需要判断一下信息。如果不是草稿状态的时候，VIN号是不可以修改的。
        if (!RegisterDic.STATUS_ZORO_DRAFT.equals(temp.getStatus())) {
            if (!temp.getVin().equals(channel.getVin())) {
                return IResponse.fail("修改失败，停用状态不可以修改VIN号！");
            }
        }
        List<String> statusList =new ArrayList<>();
        statusList.add(RegisterDic.STATUS_STOP);
        statusList.add(RegisterDic.STATUS_REFUSE);
        statusList.add(RegisterDic.STATUS_ZORO_DRAFT);
        // 先查看这个VIN在其他挂靠单位有没有未失效的备案信息 排除了自己再查的
        if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getChannelId, channel.getChannelId()).notIn(ChannelListingCarTemp::getId, channel.getId()).notIn(ChannelListingCarTemp::getStatus, statusList)).size() > 0) {
            return IResponse.fail("该挂牌车在其他合作商存在未失效的备案信息！");
        }

        // 先根据状态和VIN号判断VIN号是否重复
        if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getId, channel.getId()).notIn(ChannelListingCarTemp::getStatus, statusList)).size() > 0) {
            return IResponse.fail("修改失败，该挂牌车已存在未失效的备案信息！");
        } else {
            // 修改车辆的信息
            channel.setUpdateTime(new Date(System.currentTimeMillis()));
            channel.setUpdateBy(SecurityUtils.getUsername());
            channel.setChannelBelong(baseInfoTemp.getChannelBelong());
            if(channel.getFirstLicensePlateDate()==null){
                channelListingCarTempService.update(Wrappers.<ChannelListingCarTemp>lambdaUpdate().set(ChannelListingCarTemp::getFirstLicensePlateDate,null).eq(ChannelListingCarTemp::getId, channel.getId()));
            }
            if(RegisterDic.STATUS_PASS.equals(channel.getStatus())){
                channel.setApprovalTime(new Date(System.currentTimeMillis()));
            }
            channelListingCarTempService.updateById(channel);

            // 如果是通过同步数据
            ChannelListingCarTemp cc =channelListingCarTempService.getById(channel.getId());
            if(RegisterDic.STATUS_PASS.equals(cc.getStatus())){
                comAttachementFileTempService.remove(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,channel.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.carRecordApply.toString()));
                //把影像资料存储
                List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,channel.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.carRecordApply.toString()));
                if(fileList.size()>0){
                    for(ComAttachmentFile file:fileList){
                        ComAttachementFileTemp fileTemp=new ComAttachementFileTemp();
                        BeanUtils.copyProperties(file, fileTemp);
                        fileTemp.setId(null);
                        comAttachementFileTempService.save(fileTemp);
                    }
                    List<ComAttachementFileTemp> tempList=comAttachementFileTempService.list(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,channel.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.carRecordApply.toString()));
                    if(tempList.size()>0){
                        List<ComAttachmentFile> list2 = JSONUtil.parseArray(tempList).toList(ComAttachmentFile.class);
                        ComAttachmentFileDataVo dataVo=new ComAttachmentFileDataVo();
                        dataVo.setComAttachmentFileList(list2);
                        AfsTransEntity<ComAttachmentFileDataVo> transEntity = new AfsTransEntity<>();
                        transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_CHANNEL_FILE_APPLY);
                        transEntity.setData(dataVo);
                        senderChannelToApply.sendWitnessFile(transEntity);
                    }
                }
                this.sendStorehouse(channel);
            }
            return IResponse.success(Boolean.TRUE).setMsg("修改成功！");


        }
    }

    @Transactional
    @PostMapping("/applyEdit")
    @ApiOperation(value = "修改数据")
    public IResponse<ChannelListingCarTemp> applyEdit(@RequestBody ChannelListingCarTemp channel) throws ParseException, JsonProcessingException {
        if (channel.getChannelId() == null) {
            return IResponse.fail("请选择合作商！");
        }
        // 获取关联表id
        if (channel.getId() == null) {
            return IResponse.fail("请正确信息后修改！");
        }
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());
        comAttachmentFileService.remove(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,channel.getId().toString()).eq(ComAttachmentFile::getBelongNo, ChannelNode.carRecordApply.toString()));
        if(channel.getFileList().size()>0){
            for (ComAttachmentFile FileList :channel.getFileList()){
                ComAttachmentFile file =new ComAttachmentFile();
                BeanUtils.copyProperties(FileList, file);
                file.setId(null);
                comAttachmentFileService.save(file);
            }

        }
        ChannelListingCarTemp temp = channelListingCarTempService.getById(channel.getId());

        //修改前需要判断一下信息。如果不是草稿状态的时候，VIN号是不可以修改的。
        if (!RegisterDic.STATUS_ZORO_DRAFT.equals(temp.getStatus())) {
            if (!temp.getVin().equals(channel.getVin())) {
                return IResponse.fail("修改失败，停用状态不可以修改VIN号！");
            }
        }
        List<String> statusList =new ArrayList<>();
        statusList.add(RegisterDic.STATUS_STOP);
        statusList.add(RegisterDic.STATUS_REFUSE);
        statusList.add(RegisterDic.STATUS_ZORO_DRAFT);
        // 先查看这个VIN在其他挂靠单位有没有未失效的备案信息 排除了自己再查的
        if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getChannelId, channel.getChannelId()).notIn(ChannelListingCarTemp::getId, channel.getId()).notIn(ChannelListingCarTemp::getStatus, statusList)).size() > 0) {
            return IResponse.fail("该挂牌车在其他合作商存在未失效的备案信息！");
        }

        // 先根据状态和VIN号判断VIN号是否重复
        if (channelListingCarTempService.list(Wrappers.<ChannelListingCarTemp>query().lambda().eq(ChannelListingCarTemp::getVin, channel.getVin()).notIn(ChannelListingCarTemp::getId, channel.getId()).notIn(ChannelListingCarTemp::getStatus, statusList)).size() > 0) {
            return IResponse.fail("修改失败，该挂牌车已存在未失效的备案信息！");
        } else {
            // 修改车辆的信息
            channel.setUpdateTime(new Date(System.currentTimeMillis()));
            channel.setUpdateBy(SecurityUtils.getUsername());
            channel.setChannelBelong(baseInfoTemp.getChannelBelong());
            if(channel.getFirstLicensePlateDate()==null){
                channelListingCarTempService.update(Wrappers.<ChannelListingCarTemp>lambdaUpdate().set(ChannelListingCarTemp::getFirstLicensePlateDate,null).eq(ChannelListingCarTemp::getId, channel.getId()));
            }
            channel.setMsgSource(RegisterDic.sourceApply);
            channelListingCarTempService.updateById(channel);
            // 重新查一遍数据
            ChannelListingCarTemp listingCarTemp=channelListingCarTempService.getById(channel.getId());
            // 如果是审核中 那么就进入工作流
            if(RegisterDic.STATUS_APPROVE.equals(listingCarTemp.getStatus())){
                // 如果是被退回进来的
                if(RegisterDic.STATUS_RETURN.equals(temp.getStatus())){
                    this.sendWorkflow(listingCarTemp);
                }else {
                    //说明之前被同意过又新发起了
                    this.foundWorkFlow(listingCarTemp);
                }
            }
            return IResponse.success(Boolean.TRUE).setMsg("修改成功！");


        }
    }
    // 发起一个新的工作流
    public  void foundWorkFlow (ChannelListingCarTemp listingCarTemp) throws JsonProcessingException {
        StartFlowRequest startFlowNew = new StartFlowRequest();
        startFlowNew.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_REGISTER));
        startFlowNew.setBizDataId(uidGenerator.getUID()+"");
        startFlowNew.setFlowName((StringUtils.isEmpty(listingCarTemp.getOwnerName())?"":(listingCarTemp.getOwnerName())+"-")+AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_REGISTER));
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(listingCarTemp);
        JSONObject cancelJson = JSONObject.parseObject(json);
        // 判断渠道归属
        if(listingCarTemp.getChannelBelong()==""||listingCarTemp.getChannelBelong()==null){
            throw new AfsBaseException("获取渠道归属失败！");
        }else {
            cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BELONG),listingCarTemp.getChannelBelong());
        }
        workflowService.startWorkFlow(startFlowNew,cancelJson);

        //保存业务相关数据、用户前端逻辑判断
        WorkTaskDetail detail = new WorkTaskDetail();
        detail.setBizDataId(startFlowNew.getBizDataId());
        detail.setName(listingCarTemp.getOwnerName());
        detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_REGISTER));
        //挂牌车id绑定
        detail.setBusinessKey(listingCarTemp.getId());
        workTaskDetailService.save(detail);

        // 给挂牌车数据绑定工作流实例id
        listingCarTemp.setDataId(Long.valueOf(startFlowNew.getBizDataId()));
        channelListingCarTempService.updateById(listingCarTemp);
    }
    //  发起工作流的方法
    public void sendWorkflow(ChannelListingCarTemp listingCarTemp) throws JsonProcessingException {
        //发起挂牌车审核流程
        WorkTaskDetail workTaskDetail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda()
                .eq(WorkTaskDetail::getBusinessKey, listingCarTemp.getId().toString()).eq(WorkTaskDetail::getBizDataId,listingCarTemp.getDataId().toString()));
        if(workTaskDetail ==null){
            this.foundWorkFlow(listingCarTemp);
        }else {
            WorkTaskDetail work =workTaskDetailService.list(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBusinessKey, listingCarTemp.getId()).eq(WorkTaskDetail::getBizDataId,listingCarTemp.getDataId().toString())).get(0);
            // 如果是通过
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(listingCarTemp.getId());
            dto.setApprove("1");
            dto.setBizDataId(listingCarTemp.getDataId().toString());

            submit(dto);

        }

    }

    @ApiOperation(value = "通过id删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public IResponse<Boolean> delete(@RequestBody ChannelListingCarTemp channel) {

        if (channel.getId() == null) {
            return IResponse.fail("请选择正确信息后删除！");
        }
        channelListingCarTempService.removeById(channel.getId());
        return new IResponse<Boolean>().setMsg("通过id删除数据成功");
    }

    @ApiOperation(value = "通过id，修改挂靠单备案状态")
    @RequestMapping(value = "/upStatus", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public IResponse<Boolean> upStatus(@RequestBody ChannelListingCarTemp channel) {

        if (channel.getId() == null) {
            return IResponse.fail("请选择正确信息后删除！");
        }
        // 先根据id 查这个信息
        ChannelListingCarTemp chan = channelListingCarTempService.getById(channel.getId());
        chan.setStatus(channel.getStatus());
        chan.setUpdateTime(new Date(System.currentTimeMillis()));
        chan.setUpdateBy(SecurityUtils.getUsername());
        channelListingCarTempService.updateById(chan);
        this.sendStorehouse(chan);
        return new IResponse<Boolean>().setMsg("状态修改成功！");
    }


    @RequestMapping(value = "/delAllByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除挂靠车备案信息")
    @Transactional
    @SysLog("批量通过ids删除")
    public IResponse<Boolean> delAllByIds(@PathVariable String[] ids) {

        channelListingCarTempService.removeByIds(Arrays.asList(ids));

        return new IResponse<Boolean>().setMsg("批量通过id删除数据成功");
    }

    @RequestMapping(value = "/upAllByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids停用挂靠车备案信息")
    @Transactional
    @SysLog("批量通过ids停用")
    public IResponse<Boolean> upAllByIds(@PathVariable String[] ids) {
        for (int j = 0; j < Arrays.asList(ids).size(); j++) {
            Long id = Long.valueOf(Arrays.asList(ids).get(j));
            ChannelListingCarTemp temp = channelListingCarTempService.getById(id);
            if (!RegisterDic.STATUS_STOP.equals(temp.getStatus())) {
                temp.setStatus(RegisterDic.STATUS_STOP);
                temp.setUpdateTime(new Date(System.currentTimeMillis()));
                temp.setUpdateBy(SecurityUtils.getUsername());
                temp.setCeaseTime(new Date(System.currentTimeMillis()));
                channelListingCarTempService.updateById(temp);

                this.sendStorehouse(temp);
            }
        }


        return new IResponse<Boolean>().setMsg("批量通过id停用成功");
    }

    @Transactional
    @PostMapping("/upApplyAllByIds")
    @ApiOperation(value = "根据id批量停用,为进件提供的接口")
    public IResponse<Boolean> upApplyAllByIds(@RequestBody String idaa) {
        String[] ids = idaa.split(",");
        for (int j = 0; j < Arrays.asList(ids).size(); j++) {
            Long id = Long.valueOf(Arrays.asList(ids).get(j));
            ChannelListingCarTemp temp = channelListingCarTempService.getById(id);
            if (!RegisterDic.STATUS_STOP.equals(temp.getStatus())) {
                temp.setStatus(RegisterDic.STATUS_STOP);
                temp.setUpdateTime(new Date(System.currentTimeMillis()));
                temp.setUpdateBy(SecurityUtils.getUsername());
                temp.setCeaseTime(new Date(System.currentTimeMillis()));
                channelListingCarTempService.updateById(temp);
                this.sendStorehouse(temp);
            }
        }
        return new IResponse<Boolean>().setMsg("批量通过id停用成功");
    }


    @PostMapping("/getCarByVin")
    @ApiOperation(value = "根据VIN号和合作商id")
    public Object getCarByVin(@RequestBody JSONObject json) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Long channelId = json.getLong("channelId");
            String vin = json.getString("vin");
            if (channelId == null || vin == null || vin == "") {
                return IResponse.fail("请输入合作商和VIN号！");
            }
            List<ChannelListingCarTempVo> list = channelListingCarTempService.getCarByVin(channelId, vin);
            resultMap.put("ListingCarList", list);
            resultMap.put("code", "0000");
            if (list.size() > 0) {
                resultMap.put("msg", "success");
            } else {
                resultMap.put("msg", "未查询到数据！");
            }
        } catch (Exception e) {
            resultMap.put("code", "9999");
            resultMap.put("msg", "查询失败！");
            logger.error(e.getMessage(), e);
        }
        return resultMap;

    }


    @PostMapping("/downloadReport")
    public void downloadReport(HttpServletResponse response, @RequestBody ChannelListingCarTemp channel) {
        ChannelListingCarTemp temp =channelListingCarTempService.getById(channel.getId());
        ChannelBaseInfoTemp baseInfoTemp =channelBaseInfoTempService.getById(temp.getChannelId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PrintCar car =new PrintCar();
        car.setChannelName(baseInfoTemp.getChannelFullName());
        if (temp.getGuidancePrice()!=null){
            car.setGuidancePrice(temp.getGuidancePrice().toString());
        }else {
           car.setGuidancePrice("");
        }
        if(temp.getEvaluationPrice()!=null){
            car.setEvaluationPrice(temp.getEvaluationPrice().toString());
        }else {
            car.setEvaluationPrice("");
        }
        if(temp.getBrand()!=null){
            car.setBrand(temp.getBrand());
        }else {
            car.setBrand("");
        }
        if(temp.getModel()!=null){
            car.setModel(temp.getModel());
        }else {
            car.setModel("");
        }
        if(temp.getStyle()!=null){
            car.setStyle(temp.getModel());
        }else {
            car.setStyle("");
        }
        if(temp.getOwnerName()!=null){
            car.setOwnerName(temp.getOwnerName());
        }else {
            car.setOwnerName("");
        }
        if(temp.getCarNumber()!=null){
            car.setCarNumber(temp.getCarNumber());
        }else {
            car.setCarNumber("");
        }
        if(temp.getVin()!=null){
            car.setVin(temp.getVin());
        }else {
            car.setVin("");
        }
        if(temp.getEngineNumber()!=null){
            car.setEngineNumber(temp.getEngineNumber());
        }else {
            car.setEngineNumber("");
        }
        if(temp.getManufactureDate()!=null){
            car.setManufactureDate(sdf.format(temp.getManufactureDate()));
        }else {
            car.setManufactureDate("");
        }
        if(temp.getInvoiceTime()!=null){
            car.setInvoiceTime(sdf.format(temp.getInvoiceTime()));
        }else {
            car.setInvoiceTime("");
        }
        if(temp.getApparentMileage()!=null){
            car.setApparentMileage(temp.getApparentMileage());
        }else {
            car.setApparentMileage("");
        }
        if(temp.getBodyColor()!=null){
            car.setBodyColor(temp.getBodyColor());
        }else {
            car.setBodyColor("");
        }
        if(temp.getTransferNumber()!=null){
            car.setTransferNumber(temp.getTransferNumber().toString());
        }else {
            car.setTransferNumber("");
        }
        if(temp.getOutputVolume()!=null){
            car.setOutputVolume(temp.getOutputVolume());
        }else {
            car.setOutputVolume("");
        }
        //  翻译省市
        if(temp.getCardCity()!=null){
            TsysAddressParam p =tsysAddressParamService.getProvinceOrCtiy(temp.getCardProvince());
            TsysAddressParam c =tsysAddressParamService.getProvinceOrCtiy(temp.getCardCity());
            car.setRegion(p.getLabel()+"/"+c.getLabel());
        }else {
            car.setRegion("");
        }
        if(temp.getFirstLicensePlateDate()!=null){
            car.setFirstLicensePlateDate(sdf.format(temp.getFirstLicensePlateDate()));
        }else {
            car.setFirstLicensePlateDate("");
        }
        if("1".equals(temp.getUseCarNumber())){
            car.setCarCodeYes("■");
            car.setCarCodeNo( "□");
        }else {
            car.setCarCodeYes( "□");
            car.setCarCodeNo("■");
        }
        if(temp.getApprovalTime()!=null){
            car.setApprovalTime(sdf.format(temp.getApprovalTime()));
        }else {
            car.setApprovalTime("");
        }
        // 生成模板
        JSONObject jsonTemp = (JSONObject) JSONObject.toJSON(car);
        // 规则VO
        CarRule rule=new CarRule();
        rule.setUseCarNumber(temp.getUseCarNumber());
        // 下面那个是规则
        JSONObject jsonRule = (JSONObject) JSONObject.toJSON(rule);
        List<ComAttachmentFile> fileList = comPrintFormManageService.batchPrint(jsonTemp, jsonRule, channel.getId().toString(), "printLoanChannel","");
        if(fileList.size()<=0){
            throw new AfsBaseException("未找到模板！");
        }
        ComAttachmentFile attachmentFile = fileList.get(0);
        byte[] fileByte = comAttachmentFileService.downloadAttachmentFile(attachmentFile);
        BufferedInputStream bufferedInputStream = null;
        try {
            response.reset(); // 重点突出
            if (fileByte.length > 0) {
                bufferedInputStream = new BufferedInputStream(IoUtil.toStream(fileByte));
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;filename=" + HttpUtil.encodeUtf8(attachmentFile.getFileName()));
                IoUtil.copy(bufferedInputStream, response.getOutputStream(), 1024);
                response.getOutputStream().flush();
                IoUtil.close(bufferedInputStream);
                return ;
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            IoUtil.close(bufferedInputStream);
            log.error("文件下载失败:" + e.getMessage());
        } finally {
            IoUtil.close(bufferedInputStream);
        }
    }



}
